# reflection_engine/reflection.py (增强版)
import json
from datetime import datetime, timedelta
import sys
import os
from typing import Dict, List, Optional, Any

sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from memory_system.memory_manager import MemoryManager

class ReflectionEngine:
    """增强版反思引擎 - 利用多种记忆类型进行深度分析"""
    
    def __init__(self, memory_manager):
        self.memory_manager = memory_manager
        print("🧠 增强版反思引擎初始化完成")
    
    def trigger_comprehensive_reflection(self, user_id: str, reflection_type: str = "auto") -> Dict:
        """
        综合反思过程 - 利用所有记忆类型进行深度分析
        """
        print(f"🔍 触发综合反思 - 用户: {user_id}, 类型: {reflection_type}")
        
        try:
            # 1. 收集各类记忆数据
            reflection_data = self._collect_reflection_data(user_id)
            
            if not reflection_data.get("has_data"):
                return {
                    "status": "no_data",
                    "message": "没有足够的记忆数据进行分析"
                }
            
            # 2. 深度分析学习状态
            learning_analysis = self._analyze_learning_state(reflection_data)
            
            # 3. 构建增强版反思提示词
            reflection_prompt = self._build_comprehensive_prompt(reflection_data, learning_analysis)
            
            # 4. 模拟调用百炼Agent
            reflection_result = self._simulate_bailian_reflection(reflection_prompt)
            
            # 5. 将深度分析结果写入记忆
            if reflection_result.get("insights"):
                for insight in reflection_result["insights"]:
                    self.memory_manager.write_memory(
                        user_id=user_id,
                        content=insight,
                        memory_type="derived_knowledge",
                        metadata={
                            "source": "comprehensive_reflection",
                            "reflection_type": reflection_type,
                            "analysis_depth": "deep"
                        },
                        importance=0.9
                    )
            
            print("✅ 综合反思过程完成")
            return {
                "status": "success",
                "user_id": user_id,
                "reflection_type": reflection_type,
                "learning_analysis": learning_analysis,
                "ai_insights": reflection_result,
                "timestamp": datetime.now().isoformat()
            }
            
        except Exception as e:
            error_msg = f"综合反思过程失败: {e}"
            print(f"❌ {error_msg}")
            return {"status": "error", "message": error_msg}
    
    def _collect_reflection_data(self, user_id: str) -> Dict:
        """收集反思所需的各种数据"""
        data = {
            "user_id": user_id,
            "collection_time": datetime.now().isoformat(),
            "has_data": False
        }
        
        try:
            # 获取各类记忆
            data["recent_interactions"] = self.memory_manager.read_memory(
                user_id, memory_type="interaction", limit=15
            )
            data["mistakes"] = self.memory_manager.get_user_mistakes(user_id, recent_days=30)
            data["progress"] = self.memory_manager.get_learning_progress(user_id)
            data["knowledge_gaps"] = self.memory_manager.get_knowledge_gap_analysis(user_id)
            data["derived_knowledge"] = self.memory_manager.read_memory(
                user_id, memory_type="derived_knowledge", limit=10
            )
            
            # 检查是否有足够数据
            total_memories = (
                len(data["recent_interactions"]) + 
                len(data["mistakes"]) + 
                len(data["derived_knowledge"])
            )
            data["has_data"] = total_memories > 2
            
        except Exception as e:
            print(f"❌ 数据收集失败: {e}")
        
        return data
    
    def _analyze_learning_state(self, data: Dict) -> Dict:
        """分析学习状态"""
        analysis = {
            "learning_momentum": "unknown",
            "knowledge_stability": "unknown",
            "improvement_areas": [],
            "strengths": []
        }
        
        try:
            # 分析学习动力
            recent_interactions = len(data.get("recent_interactions", []))
            if recent_interactions > 10:
                analysis["learning_momentum"] = "high"
            elif recent_interactions > 5:
                analysis["learning_momentum"] = "medium"
            else:
                analysis["learning_momentum"] = "low"
            
            # 分析知识稳定性（基于错题）
            mistakes = data.get("mistakes", [])
            if mistakes:
                recent_mistakes = [m for m in mistakes if self._is_recent(m.get("metadata", {}).get("timestamp", ""), days=7)]
                if len(recent_mistakes) < len(mistakes) * 0.3:
                    analysis["knowledge_stability"] = "improving"
                else:
                    analysis["knowledge_stability"] = "needs_work"
            
            # 分析改进领域和优势
            knowledge_gaps = data.get("knowledge_gaps", {})
            weak_points = knowledge_gaps.get("weak_knowledge_points", [])
            if weak_points:
                analysis["improvement_areas"] = [wp["point"] for wp in weak_points[:3]]
            
            # 基于进度识别优势
            progress_data = data.get("progress", {})
            course_progress = progress_data.get("course_progress", {})
            for course, data in course_progress.items():
                if data.get("average_progress", 0) > 0.8:
                    analysis["strengths"].append(course)
        
        except Exception as e:
            print(f"❌ 学习状态分析失败: {e}")
        
        return analysis
    
    def _is_recent(self, timestamp: str, days: int = 7) -> bool:
        """检查时间戳是否在最近指定天数内"""
        try:
            if not timestamp:
                return False
            record_time = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
            return (datetime.now() - record_time).days <= days
        except:
            return False
    
    def _build_comprehensive_prompt(self, data: Dict, analysis: Dict) -> str:
        """构建综合反思提示词"""
        
        prompt_sections = []
        
        # 学习进度部分
        progress_data = data.get("progress", {})
        if progress_data:
            prompt_sections.append(f"学习进度概况: {json.dumps(progress_data, ensure_ascii=False, indent=2)}")
        
        # 错题分析部分
        mistakes = data.get("mistakes", [])
        if mistakes:
            mistake_summary = []
            for i, mistake in enumerate(mistakes[:5], 1):
                metadata = mistake.get("metadata", {})
                mistake_summary.append(f"{i}. 知识点: {metadata.get('knowledge_points', '未知')}, 错误: {mistake['content'][:50]}...")
            prompt_sections.append(f"近期错题: {json.dumps(mistake_summary, ensure_ascii=False, indent=2)}")
        
        # 知识缺口部分
        knowledge_gaps = data.get("knowledge_gaps", {})
        if knowledge_gaps:
            prompt_sections.append(f"知识缺口分析: {json.dumps(knowledge_gaps, ensure_ascii=False, indent=2)}")
        
        # 学习状态分析
        prompt_sections.append(f"学习状态评估: {json.dumps(analysis, ensure_ascii=False, indent=2)}")
        
        comprehensive_prompt = f"""
作为智能医学工程教育专家，请基于以下全面的学生学习数据生成深度教育洞察：

{chr(10).join(prompt_sections)}

请进行深度分析并回答：
1. 该学生的整体学习健康状况如何？存在哪些潜在风险？
2. 基于错题模式和知识缺口，最急需改进的3个领域是什么？
3. 如何利用学生的优势领域来帮助薄弱领域的学习？
4. 生成3-4条具体的、可操作的"教学洞察"，用于个性化辅导规划。

请用JSON格式回复：
{{
    "learning_health": "整体评价文本",
    "urgent_improvements": ["领域1", "领域2", "领域3"],
    "strength_utilization": "如何利用优势的文本",
    "teaching_insights": ["洞察1", "洞察2", "洞察3", "洞察4"]
}}
"""
        return comprehensive_prompt
    
    def _simulate_bailian_reflection(self, prompt):
        """模拟百炼Agent的深度反思过程"""
        print("🤖 模拟百炼Agent深度反思分析...")
        
        # 模拟深度AI分析结果
        simulated_result = {
            "learning_health": "学生学习动力中等，知识稳定性正在改善，但在核心概念理解上存在明显缺口",
            "urgent_improvements": [
                "医学影像预处理技术",
                "深度学习模型调参方法", 
                "交叉验证在医学数据中的应用"
            ],
            "strength_utilization": "利用学生在医学人工智能课程中的良好基础，通过类比教学帮助理解薄弱环节",
            "teaching_insights": [
                "建议采用项目式学习，让学生在实际医学影像分析项目中应用所学知识",
                "需要加强基础概念的巩固，特别是图像预处理流程",
                "推荐间隔重复练习，针对错题涉及的知识点进行专项训练",
                "建议引入真实医学案例，增强学习的实用性和趣味性"
            ]
        }
        
        return simulated_result

# 测试增强版反思引擎
def test_enhanced_reflection():
    """测试增强版反思引擎"""
    print("🧪 测试增强版反思引擎...")
    
    try:
        # 初始化记忆管理器
        mm = MemoryManager()
        
        # 初始化反思引擎
        re = ReflectionEngine(mm)
        
        # 测试综合反思
        result = re.trigger_comprehensive_reflection("med_student_001", "deep")
        
        print("综合反思结果:")
        print(json.dumps(result, ensure_ascii=False, indent=2))
        
    except Exception as e:
        print(f"❌ 增强版反思测试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_enhanced_reflection()